﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using Citi.EmailSender.Domain;
using Citi.EmailSender.ConsoleUI.EmailSenderWcf;
using Citi.Helpers;
using Email = Citi.EmailSender.Domain.Email;

namespace Citi.EmailSender.ConsoleUI
{
    public class Program
    {
        private static readonly decimal LoopingMinutes = decimal.Parse(ConfigurationManager.AppSettings["LoopingMinutes"]);
        private static readonly string TempFolder = ConfigurationManager.AppSettings["TempFolder"];
        private static string Proxy { get { return ConfigurationManager.AppSettings["Proxy"]; } }
        private static string NetworkDomain { get { return ConfigurationManager.AppSettings["NetworkDomain"]; } }
        private static string NetworkUser { get { return ConfigurationManager.AppSettings["NetworkUser"]; } }
        private static string NetWorkPassword { get { return ConfigurationManager.AppSettings["NetWorkPassword"]; } }
        private static readonly string DownloadTempFolder = ConfigurationManager.AppSettings["DownloadTempFolder"];

        private static void SendPendingEmails()
        {
            WriteLine(string.Format("{0} Getting pending emails", DateTime.Now.ToString("dd/MM/yyy HH:mm:ss")));
            var emails = new Email().GetPendingEmails();
            WriteLine(string.Format("{0} Emails pending: {1}", DateTime.Now.ToString("dd/MM/yyy HH:mm:ss"), emails.Count()));

            var emailHelper = new EmailHelper(NetworkUser, NetWorkPassword, NetworkDomain, Proxy);
            Util.DownloadTempFolder = DownloadTempFolder;
            Util.NetWorkPassword = NetWorkPassword;
            Util.NetworkDomain = NetworkDomain;
            Util.NetworkUser = NetworkUser;
            Util.Proxy = Proxy;
            Util.TempFolder = TempFolder;
            Util.WebUrl = ConfigurationManager.AppSettings["WebUrl"];

            foreach (var email in emails)
            {
                var index = emails.IndexOf(email) + 1;

                try
                {
                    WriteLine(string.Format("{0} #{1} Getting email information", DateTime.Now.ToString("dd/MM/yyy HH:mm:ss"), index));

                    var emailData = Util.FillEmailData(email,index);

                    WriteLine(string.Format("{0} #{1} Sending email", DateTime.Now.ToString("dd/MM/yyy HH:mm:ss"), index));
                    emailHelper.SendEmail(emailData);
                    email.SentOn = DateTime.Now;

                    WriteLine(string.Format("{0} #{1} Updating database", DateTime.Now.ToString("dd/MM/yyy HH:mm:ss"), index));
                    email.Save(email);
                }
                catch (Exception e)
                {
                    var message = string.Concat(e.Message, (e.InnerException != null ? e.InnerException.Message : string.Empty), e.StackTrace);
                    File.WriteAllText(Path.Combine(TempFolder, "ErrorConsole.txt"), message);
                    WriteLine(message);
                    email.Tentatives++;
                    email.Save(email);

                    if (email.Tentatives == 3)
                    {
                        WriteLine(string.Format("{0} #{1} Email canceled after 3 tentatives", DateTime.Now.ToString("dd/MM/yyy HH:mm:ss"), index));

                        //    if (emailData == null) continue;

                        //    emailData.Attachments = null;
                        //    emailData.Bcc = null;
                        //    emailData.To = email.OnBehalfOf.EmailAddress ;
                        //    emailData.Cc = null;
                        //    emailData.BodyMessage = message;
                        //    emailData.Subject = string.Concat("Error: ", emailData.Subject);

                        //    emailHelper.SendEmail(emailData);
                    }
                }
            }
        }

        private static void WriteLine(string value)
        {
            try
            {
                Console.WriteLine(value);
                File.AppendAllLines(Path.Combine(TempFolder, "EmailSenderLog.txt"), new List<string> { value });
            }
            catch { }
        }
        
        static void Main(string[] args)
        {
            //DownloadAttachments();
            ExecuteActions();
            //InsertInQueue();
            //DownloadAttachment();
        }

        private static void DownloadAttachments()
        {
            WriteLine(string.Format("{0} Getting pending attachment download ", DateTime.Now.ToString("dd/MM/yyy HH:mm:ss")));
            var pendingDownloads = new Domain.DownloadAttachment().GetPendingDownloads().ToList();
            WriteLine(string.Format("{0} Downloads pending: {1}", DateTime.Now.ToString("dd/MM/yyy HH:mm:ss"), pendingDownloads.Count()));

            foreach (var pendingDownload in pendingDownloads)
            {
                try
                {
                    var attachment = new EmailHelper.DownloadAttachmentData
                        {
                            DefaultFolder = (EmailHelper.DefaultFolders)pendingDownload.DefaultFolder,
                            InitialDate = pendingDownload.InitialDate,
                            NonDefaultFolder = pendingDownload.NonDefaultFolder,
                            PartialFileName = pendingDownload.PartialFileName,
                            PartialSubject = pendingDownload.Subject,
                            PathToSave = Path.Combine(DownloadTempFolder, pendingDownload.DownloadFolder),
                            FileExtensions = string.IsNullOrEmpty(pendingDownload.FileExtensions) ? null : pendingDownload.FileExtensions.Split('|').ToList()
                        };

                    WriteLine(string.Format("{0} #{1} Downloading attachment", DateTime.Now.ToString("dd/MM/yyy HH:mm:ss"), pendingDownloads.IndexOf(pendingDownload) + 1));
                    new EmailHelper(NetworkUser, NetWorkPassword, NetworkDomain, Proxy).DownloadAttachment(attachment);
                    WriteLine(string.Format("{0} #{1} Attachment downloaded", DateTime.Now.ToString("dd/MM/yyy HH:mm:ss"), pendingDownloads.IndexOf(pendingDownload) + 1));
                }
                finally
                {
                    pendingDownload.DownloadedOn = DateTime.Now;
                    pendingDownload.Save(pendingDownload);
                }
            }
        }

        private static void InsertInQueue()
        {
            using (var client = new EmailClient())
            {
                var email = new EmailSenderWcf.Email
                    {
                        BodyMessage = "<html><body><b>Teste remoto</b>[Parametro]</body></html>",
                        //BodyMessage = "teste message",
                        Subject = "Teste",
                        SentOnBehalfOfName = "guedini@live.com",
                        To =
                            new List<EmailSenderWcf.EmailAddress>
                                {
                                    new EmailSenderWcf.EmailAddress {Description = "guedini@yahoo.com"},
                                    new EmailSenderWcf.EmailAddress {Description = "nathan@guedini.com.br"}
                                },
                        Cc = new List<EmailSenderWcf.EmailAddress> { new EmailSenderWcf.EmailAddress { Description = "nathanguedini@gmail.com" } },
                        ApplicationName = "I7",
                        NeedApprovalToSend = true,
                        Parameters = new Dictionary<string, string> { { "[Parametro]", "Nathan" } },
                        ScheduleDateTime = DateTime.Now.AddMinutes(5)
                    };

                client.InsertEmailInQueue(email);
            }
        }

        private static void TestDownloadAttachment()
        {
            using (var client = new EmailClient())
            {
                var attachment = new EmailSenderWcf.DownloadAttachment
                {
                    ApplicationId = 1,
                    DefaultFolder = EmailHelper.DefaultFolders.Inbox,
                    // DownloadFolder = @"\\lacbra800w0273\c$\temp\EmailAttachment",
                    InitialDate = DateTime.Today.AddMonths(-1),
                    Subject = "Teste anexo"
                };

                var path = client.DownloadAttachment(attachment);
            }
        }

        private static void ExecuteActions()
        {
            while (true)
            {
                try
                {
                    EmailTxtData.ImportEmails();
                    SendPendingEmails();
                    DownloadAttachments();
                }
                catch(Exception e)
                {
                    WriteLine(string.Format("Error: {0}", e.Message));
                }
                finally
                {
                    WriteLine(string.Format("{0} Snoozing for {1} minute{2}",
                                            DateTime.Now.ToString("dd/MM/yyy HH:mm:ss"),
                                            LoopingMinutes,
                                            LoopingMinutes > 1 ? "s" : string.Empty));

                    System.Threading.Thread.Sleep(Convert.ToInt32(Math.Round(LoopingMinutes * 60000, 0)));
                    WriteLine(string.Empty);
                }
            }
        }
    }
}